<template>
  <a-spin :spinning="globalLoading" size="large">
    <div class="operation">
      <div class="top current-header">
        <header>
          <div class="operation-search">
            <a-form layout="inline">
              <a-form-item label="计划生产日期">
                <a-range-picker
                  format="YYYY-MM-DD"
                  @change="onTime"
                  v-model="defaulttimeList"
                >
                  <template slot="dateRender" slot-scope="current">
                    <div
                      class="ant-calendar-date"
                      :style="getcurrentStyle(current)"
                    >
                      {{ current.date() }}
                    </div>
                  </template>
                </a-range-picker>
              </a-form-item>
              <a-form-item label="厂区：">
                <a-select
                  :allowClear="true"
                  mode="multiple"
                  :maxTagCount="1"
                  class="selectwidth"
                  v-model="searchItem.WSType"
                  placeholder="请选择"
                  @change="handleChange"
                >
                  <a-select-option
                    v-for="item in WSTypeList"
                    :key="item.type"
                    :value="item.type"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="车间：">
                <a-select
                  :allowClear="true"
                  class="selectwidth"
                  v-model="searchItem.SegmentID"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in QSegmentList"
                    :key="item.type"
                    :value="item.type"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="已分配：">
                <a-select
                  :allowClear="true"
                  mode="multiple"
                  :maxTagCount="1"
                  class="selectwidth"
                  v-model="searchItem.IsDistribute"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in DicIsDistribute"
                    :key="item.type"
                    :value="item.type"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="计划单状态：">
                <a-select
                  :allowClear="true"
                  mode="multiple"
                  :maxTagCount="1"
                  class="selectwidth"
                  v-model="searchItem.State"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in DicStatus"
                    :key="item.type"
                    :value="item.type"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="计划单号：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.PackingPlanNo"
                />
              </a-form-item>
              <a-form-item label="产品编码：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.MaterialCode"
                />
              </a-form-item>
              <a-form-item label="产品名称：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.MaterialName"
                />
              </a-form-item>
              <a-form-item label="销售单号：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.SellOrderNo"
                />
              </a-form-item>
              <a-form-item label="MRP控制者：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.MRPUser"
                />
              </a-form-item>
              <a-form-item label="计划员：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.PlanUser"
                />
              </a-form-item>
            </a-form>
            <div style="margin-left: auto">
              <a-button class="default-button button" @click="getData"
                >查询</a-button
              >
              <general-button
                class="button"
                @operation="addMultipleFun"
                btn-text="批量新增"
                btnPowerNum="8EFF64AE-79BD-466C-8490-8F56D312F30C"
              ></general-button>
              <general-button
                class="button"
                @operation="issueMultipleFun"
                btn-text="批量下发"
                btnPowerNum="0C4ECCCF-DF4B-42D4-BFFB-088498314D3A"
              ></general-button>
              <a-button
                class="default-button button"
                @click="alreadyShow = true"
              >
                已分配精华液
              </a-button>
            </div>
          </div>
        </header>
        <section>
          <div class="table-basic-box">
            <a-table
              className="components-table-demo-nested"
              :columns="topColumns"
              :row-key="(record) => record.PackingPlanID"
              :data-source="dataPage.Data"
              :customRow="customRow"
              :scroll="{ y: 300, x: 1500 }"
              :pagination="false"
              size="middle"
              :row-selection="{
                selectedRowKeys: topRowKey,
                onChange: topTableChangeFun,
                fixed: true,
              }"
            >
              <template slot="name" slot-scope="name">
                {{ name }}
              </template>
              <template slot="action" slot-scope="text, record">
                <div class="chart-manage">
                  <general-button
                    @operation="addFun(record)"
                    btn-text="新增"
                    :disabled="record.DistributeState > 0"
                    btnPowerNum="8EFF64AE-79BD-466C-8490-8F56D312F30C"
                    class="small-button"
                  ></general-button>
                  <general-button
                    @operation="editFun(record)"
                    btn-text="修改"
                    btnPowerNum="8C85AFF6-145E-42CF-8A7D-3FF07460B68F"
                    :disabled="record.DistributeState == 0"
                    class="small-button"
                  ></general-button>
                  <general-button
                    @operation="issueFun(record)"
                    :btn-text="record.DistributeState == 2 ? '反下发' : '下发'"
                    btnPowerNum="0C4ECCCF-DF4B-42D4-BFFB-088498314D3A"
                    :disabled="record.DistributeState == 0"
                    class="small-button"
                  ></general-button>
                  <general-button
                    @operation="delFun(record)"
                    btn-text="删除"
                    :disabled="record.DistributeState == 0"
                    btnPowerNum="5732DB86-D6B1-48B9-BF44-4ED855EE5F4B"
                    class="small-button red-button"
                  ></general-button>
                </div>
              </template>
            </a-table>
            <div class="table-paging">
              <a-pagination
                v-model="searchItem.pageRequestModel.pageIndex"
                show-size-changer
                :pageSize="searchItem.pageRequestModel.pageSize"
                :default-current="1"
                :pageSizeOptions="pageSizeOptions"
                :total="dataPage.TotalNumber"
                @change="onChange"
                @showSizeChange="onShowsizeChange"
              />
            </div>
          </div>
        </section>
      </div>
      <div class="bottom current-header">
        <a-tabs type="card">
          <a-tab-pane key="1" tab="精华液信息">
            <header>
              <div class="operation-search">
                <a-form layout="inline" class="btn-ant-form">
                  <a-form-item>
                    <a-button
                      class="default-button"
                      :disabled="currentRow.SemiMGoodsDistributeID == null"
                      @click="addDetailsFun"
                    >
                      添加精华液
                    </a-button>
                  </a-form-item>
                  <a-form-item>
                    <a-button
                      class="default-button"
                      :disabled="currentRow.SemiMGoodsDistributeID == null"
                      @click="assignedShow(currentRow)"
                    >
                      已领料
                    </a-button>
                  </a-form-item>
                  <a-form-item>
                    <a-button
                      class="default-button red-button"
                      :disabled="currentRow.SemiMGoodsDistributeID == null"
                      @click="allDelDetailsFun"
                    >
                      批量删除
                    </a-button>
                  </a-form-item>
                </a-form>
              </div>
            </header>
            <section>
              <div class="table-basic-box">
                <a-table
                  className="components-table-demo-nested"
                  :columns="detailColumns"
                  :row-key="(record) => record.SemiMGoodsDistributeDetailID"
                  :data-source="semiMGoodsDistributeDetailPage.data"
                  :row-selection="{
                    selectedRowKeys: semiMGoodsDistributeDetailPage.rowKey,
                    onChange: bottomTableChangeFun,
                  }"
                  :customRow="customDetailRow"
                  :scroll="{ y: 300, x: 1500 }"
                  :pagination="false"
                  size="middle"
                >
                  <template slot="name" slot-scope="name">
                    {{ name }}
                  </template>
                  <template slot="IsLinkPlan" slot-scope="text, record">
                    <a-checkbox
                      disabled
                      v-model="record.IsLinkPlan"
                    ></a-checkbox>
                  </template>
                  <template slot="action" slot-scope="text, record">
                    <div class="chart-manage">
                      <general-button
                        @operation="editDetailsFun(record)"
                        btn-text="修改"
                        btnPowerNum="F09632A5-3206-48DA-92A5-893C6A5DB089"
                        class="small-button"
                      ></general-button>
                      <general-button
                        @operation="assignedShow(record)"
                        btn-text="已领料"
                        class="small-button"
                        :disabled="!record.RealQty > 0"
                      ></general-button>
                      <general-button
                        @operation="delDetailsFun(record)"
                        btn-text="删除"
                        btnPowerNum="DFB83B47-0A96-4D50-8D69-2345120CBBA6"
                        class="small-button red-button"
                      ></general-button>
                    </div>
                  </template>
                </a-table>
              </div>
            </section>
          </a-tab-pane>
          <a-tab-pane key="2" tab="投料单信息">
            <header>
              <div class="operation-search">
                <a-form layout="inline" class="btn-ant-form">
                  <a-form-item>
                    <a-button
                      class="default-button"
                      :disabled="currentRow.SemiMGoodsDistributeID == null"
                      @click="addPlansFun"
                    >
                      添加投料单
                    </a-button>
                  </a-form-item>
                  <a-form-item>
                    <a-button
                      class="default-button red-button"
                      :disabled="currentRow.SemiMGoodsDistributeID == null"
                      @click="allDelPlansFun"
                    >
                      批量删除
                    </a-button>
                  </a-form-item>
                </a-form>
              </div>
            </header>
            <section>
              <div class="table-basic-box">
                <a-table
                  className="components-table-demo-nested"
                  :columns="detailPlanColumns"
                  :row-key="(record) => record.SemiMGoodsPlanRelationID"
                  :data-source="semiMGoodsDistributePlanPage.data"
                  :row-selection="{
                    selectedRowKeys: semiMGoodsDistributePlanPage.rowKey,
                    onChange: bottomPlanTableChangeFun,
                  }"
                  :customRow="customPlanRow"
                  :scroll="{ y: 300, x: 1500 }"
                  :pagination="false"
                  size="middle"
                >
                  <template slot="name" slot-scope="name">
                    {{ name }}
                  </template>
                  <template slot="action" slot-scope="text, record">
                    <div class="chart-manage">
                      <general-button
                        @operation="editPlansFun(record)"
                        btn-text="修改"
                        btnPowerNum="F09632A5-3206-48DA-92A5-893C6A5DB089"
                        class="small-button"
                      ></general-button>
                      <general-button
                        @operation="delPlansFun(record)"
                        btn-text="删除"
                        btnPowerNum="DFB83B47-0A96-4D50-8D69-2345120CBBA6"
                        class="small-button red-button"
                      ></general-button>
                    </div>
                  </template>
                </a-table>
              </div>
            </section>
          </a-tab-pane>
        </a-tabs>
      </div>

      <!-- 查看已预分配弹窗 -->
      <already-form
        v-model="alreadyShow"
        @colse="alreadyShow = false"
      ></already-form>
      <!-- 添加预分配弹窗 -->
      <essence-form
        v-model="topAddShow"
        :essence-item="essenceItem || {}"
        :essence-items="essenceItems || []"
        :is-edit="dataPage.isEdit"
        @up-data="getData"
      ></essence-form>
      <!-- 添加预分配弹窗 -->
      <edit-from
        v-model="topEditShow"
        :essence-item="essenceItem"
        :is-edit="dataPage.isEdit"
        @up-data="getData"
      ></edit-from>
      <!-- 添加预分配明细弹窗 -->
      <detail-add-form
        v-model="isDetailShow"
        :essence-item="semiMGoodsDistributeDetailPage.item"
        :is-edit="semiMGoodsDistributeDetailPage.isEdit"
        :id="
          currentRow.SemiMGoodsDistributeID ||
          '00000000-0000-0000-0000-000000000000'
        "
        :semiMGoodsDistributeDetailDtos="
          currentRow.SemiMGoodsDistributeDetailDtos || []
        "
        @up-data="getData"
        @close="closeDetailForm"
      ></detail-add-form>
      <!-- 添加预分配明细弹窗 -->
      <plan-add-form
        v-model="isPlanShow"
        :essence-item="semiMGoodsDistributePlanPage.item"
        :is-edit="semiMGoodsDistributePlanPage.isEdit"
        :id="
          currentRow.SemiMGoodsDistributeID ||
          '00000000-0000-0000-0000-000000000000'
        "
        :semiMGoodsDistributeDetailDtos="
          currentRow.SemiMGoodsDistributeDetailDtos || []
        "
        @up-data="getData"
        @close="closePlanForm"
      ></plan-add-form>
      <!-- 修改预分配明细弹窗 -->
      <detail-form
        v-model="isDetailEditShow"
        :essence-item="semiMGoodsDistributeDetailPage.item"
        :is-edit="semiMGoodsDistributeDetailPage.isEdit"
        :id="
          currentRow.SemiMGoodsDistributeID ||
          '00000000-0000-0000-0000-000000000000'
        "
        @up-data="getData"
        @close="closeDetailForm"
      ></detail-form>
      <!-- 修改预分配投料单明细弹窗 -->
      <plan-form
        v-model="isPlanEditShow"
        :essence-item="semiMGoodsDistributePlanPage.item"
        :is-edit="semiMGoodsDistributePlanPage.isEdit"
        :id="
          currentRow.SemiMGoodsDistributeID ||
          '00000000-0000-0000-0000-000000000000'
        "
        @up-data="getData"
        @close="closePlanForm"
      ></plan-form>
      <!-- 查看已分配弹窗 -->

      <assigned-form
        v-model="assignedPage.isShow"
        :essenceItem="essenceItem"
      ></assigned-form>
    </div>
  </a-spin>
</template>
<script>
import { debounce } from "@/common/debounce";
import {
  getSemiMGoodsDistributeList,
  delSemiMGoodsDistribute,
  issueSemiMGoodsDistribute,
  delSemiMGoodsDistributeList,
} from "@/api/SemiMGoodsDistribute/index";

import {
  getDetailData,
  getSemiMGoodsDistributePlanList,
  delSemiMGoodsDistributeDetail,
  delSemiMGoodsDistributeDetailList,
  delSemiMGoodsPlanRelationList,
  updSemiMGoodsPlanRelation,
} from "@/api/SemiMGoodsDistributeDetail/index";
import { GetSegments } from "@/api/NBCSegment/index";
import { GetWorkShopTypesAll } from "@/api/WorkShopType/index";
import GeneralButton from "@/components/be-current-btn.vue";
import FilterDrawer from "./children/filter-drawer.vue";
import EssenceForm from "./children/preAllocation/add-essence-form.vue";
import DetailForm from "./children/preAllocationDetails/form.vue";
import PlanForm from "./children/preAllocationDetails/plan-form.vue";
import AssignedForm from "./children/assigned-from.vue";
import EditFrom from "./children/preAllocation/edit-from.vue";
import DetailAddForm from "./children/preAllocationDetails/essence-form.vue";
import AlreadyForm from "./children/preAllocationDetails/essence-form-already.vue";
import PlanAddForm from "./children/preAllocationDetails/plan-essence-form.vue";
import moment from "moment";
import { getTableScroll } from "@/common/table-calc";

export default {
  name: "PreDistributionEssence",
  components: {
    GeneralButton,
    FilterDrawer,
    EssenceForm,
    DetailForm,
    AssignedForm,
    EditFrom,
    DetailAddForm,
    PlanAddForm,
    AlreadyForm,
    PlanForm,
  },
  data() {
    return {
      searchItem: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        colResize: {
          isDragging: false,
          startX: 0,
          startWidth: 0,
          currentColIndex: -1,
        },
        createStartDt: "",
        createEndDt: "",
        orderCode: "",
        planNo: "",
        materialCodeName: "",
        batchNo: "",
        OrderType: [1],
        WSType: [],
        State: [0, 1, 2, 3],
        IsDistribute: [],
        SegmentID: null,
        MaterialCode: null,
        MaterialName: null,
        PackingPlanNo: null,
        PlanUser: null,
      }, //搜索参数
      isFilterShow: false, //更多筛选显示
      alreadyShow: false, //已分配弹窗
      topRowKey: [], //精华液选中值
      topRow: [], //精华液选中对象
      topColumns: [
        {
          title: "序号",
          dataIndex: "num",
          key: "num",
          align: "center",
          width: 50,
          fixed: "left",
        },
        {
          title: "销售单号",
          dataIndex: "SellOrderNo",
          key: "SellOrderNo",
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 1),
            },
          }),
        },
        {
          title: "预分配单号",
          dataIndex: "OrderCode",
          key: "OrderCode",
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 2),
            },
          }),
        },
        {
          title: "计划单号",
          dataIndex: "PackingPlanNo",
          key: "PackingPlanNo",
          ellipsis: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 3),
            },
          }),
        },
        {
          title: "产品编码",
          dataIndex: "MaterialCode",
          key: "MaterialCode",
          ellipsis: true,
          align: "center",
          width: 100,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 4),
            },
          }),
        },
        {
          title: "产品名称",
          dataIndex: "MaterialNmae",
          key: "MaterialNmae",
          ellipsis: true,
          align: "center",
          width: 300,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 5),
            },
          }),
        },
        {
          title: "生产车间",
          dataIndex: "SegmentName",
          key: "SegmentName",
          ellipsis: true,
          align: "center",
          width: 150,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 6),
            },
          }),
        },
        {
          title: "计划产量",
          dataIndex: "PlannedQuantity",
          key: "PlannedQuantity",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "需求/分配数",
          key: "TotalDistribute",
          align: "center",
          width: 220,
          customRender: (text, record) => {
            if (record.SemiMGoodsDistributeDetailDtos) {
              // 获取去重编码
              const codes = [
                ...new Set(
                  record.SemiMGoodsDistributeDetailDtos.map(
                    (item) =>
                      item.MaterialCode +
                      "【" +
                      item.ReqQty +
                      " / " +
                      item.AllocatedQty +
                      "】"
                  ).filter(Boolean)
                ),
              ];
              return `${codes.join("\n")}`;
            }
            return "0";
          },
        },
        {
          title: "MRP控制者",
          dataIndex: "MRPUser",
          key: "MRPUser",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "计划员",
          dataIndex: "PlanUser",
          key: "PlanUser",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "分配单状态",
          dataIndex: "DistributeStateDesc",
          key: "DistributeStateDesc",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "超分配比例(%)",
          dataIndex: "AllocationRatio",
          key: "AllocationRatio",
          ellipsis: true,
          align: "center",
          width: 120,
        },
        {
          title: "计划单状态",
          dataIndex: "StateDesc",
          key: "StateDesc",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "备注",
          dataIndex: "Remarks",
          key: "Remarks",
          ellipsis: true,
          align: "center",
          width: 200,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 6),
            },
          }),
        },
        {
          title: "创建人",
          dataIndex: "CreateUserName",
          key: "CreateUserName",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "创建时间",
          dataIndex: "CreateDtName",
          key: "CreateDtName",
          ellipsis: true,
          align: "center",
          width: 150,
        },
        {
          title: "修改人",
          dataIndex: "ModifyUserName",
          key: "ModifyUserName",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "修改时间",
          dataIndex: "ModifyDtName",
          key: "ModifyDtName",
          ellipsis: true,
          align: "center",
          width: 150,
        },
        {
          title: "操作",
          dataIndex: "operate",
          width: 230,
          align: "center",
          fixed: "right",
          scopedSlots: { customRender: "action" },
        },
      ], //预分配精华液表头
      topAddShow: false, //预分配精华液添加
      topEditShow: false, //预分配精华液修改
      essenceItem: {
        SemiMGoodsDistributeDetailID: null,
        PackingPlanID: null,
        PackingPlanNo: "",
      }, //预分配精华液添加对象
      essenceItems: [], //选择的灌装单
      defaulttimeList: [], //选择时间数组
      topTable: 0, //顶部表格高度
      bottomTable: 0, //底部表格高度
      bottomPlanTable: 0, //底部表格高度
      dataPage: {
        data: [],
        pageIndex: 1,
        pageSize: 100,
        totalNumber: 0,
        totalPage: 0,
        isEdit: false, //是否修改预分配
      },
      currentRow: { PackingPlanID: null }, //当前预分配
      semiMGoodsDistributeDetailSearch: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 100,
        },
        PackingPlanID: null,
      },
      detailColumns: [
        {
          title: "序号",
          dataIndex: "num",
          key: "num",
          align: "center",
          width: 60,
        },
        {
          title: "销售单号",
          dataIndex: "SellOrderNo",
          key: "SellOrderNo",
          ellipsis: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 20),
            },
          }),
        },
        {
          title: "投料单号",
          dataIndex: "PlanNo",
          key: "PlanNo",
          ellipsis: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 21),
            },
          }),
        },
        {
          title: "精华液编码",
          dataIndex: "MaterialCode",
          key: "MaterialCode",
          align: "center",
          width: 100,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 22),
            },
          }),
        },
        {
          title: "精华液名称",
          dataIndex: "MaterialName",
          key: "MaterialName",
          ellipsis: true,
          align: "center",
          width: 300,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 23),
            },
          }),
        },
        {
          title: "批次号",
          dataIndex: "BatchNo",
          key: "BatchNo",
          ellipsis: true,
          align: "center",
          width: 150,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 24),
            },
          }),
        },
        {
          title: "是否投料单分配",
          dataIndex: "IsLinkPlan",
          key: "IsLinkPlan",
          ellipsis: true,
          align: "center",
          width: 120,
          scopedSlots: { customRender: "IsLinkPlan" },
        },
        {
          title: "分配数量",
          dataIndex: "AllocatedQty",
          key: "AllocatedQty",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "领料数量",
          dataIndex: "RealQty",
          key: "RealQty",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "待领料数量",
          dataIndex: "ToRealQty",
          key: "ToRealQty",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "超领料数量",
          dataIndex: "OverRealQty",
          key: "OverRealQty",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "创建人",
          dataIndex: "CreateUserName",
          key: "CreateUserName",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "创建时间",
          dataIndex: "CreateDtName",
          key: "CreateDtName",
          ellipsis: true,
          align: "center",
          width: 150,
        },
        {
          title: "修改人",
          dataIndex: "ModifyUserName",
          key: "ModifyUserName",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "修改时间",
          dataIndex: "ModifyDtName",
          key: "ModifyDtName",
          ellipsis: true,
          align: "center",
          width: 150,
        },
        {
          title: "操作",
          fixed: "right",
          dataIndex: "operate",
          width: 200,
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ], //明细表头
      semiMGoodsDistributeDetailPage: {
        data: [],
        PageIndex: 1,
        PageSize: 100,
        TotalNumber: 0,
        TotalPage: 0,
        isEdit: false, //是否修改明细
        isShow: false,
        rowKey: [],
        rowItemList: [],
        item: {}, //添加的明细对象
      }, //当前明细
      currentDetailPage: {}, //当前明细
      assignedPage: {
        isShow: false,
      }, //已分配
      isDetailEditShow: false,
      isDetailShow: false,

      currentPlanRow: { PackingPlanID: null }, //当前预分配
      semiMGoodsDistributePlanSearch: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 100,
        },
        PackingPlanID: null,
      },
      detailPlanColumns: [
        {
          title: "序号",
          dataIndex: "num",
          key: "num",
          align: "center",
          width: 60,
        },
        {
          title: "销售单号",
          dataIndex: "SellOrderNo",
          key: "SellOrderNo",
          ellipsis: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 40),
            },
          }),
        },
        {
          title: "投料单号",
          dataIndex: "PlanNo",
          key: "PlanNo",
          ellipsis: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 40),
            },
          }),
        },
        {
          title: "产品编码",
          dataIndex: "MaterialCode",
          key: "MaterialCode",
          align: "center",
          width: 100,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 41),
            },
          }),
        },
        {
          title: "产品名称",
          dataIndex: "MaterialName",
          key: "MaterialName",
          ellipsis: true,
          align: "center",
          width: 300,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 42),
            },
          }),
        },
        {
          title: "批次号",
          dataIndex: "BatchNo",
          key: "BatchNo",
          ellipsis: true,
          align: "center",
          width: 150,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 43),
            },
          }),
        },

        {
          title: "分配数量",
          dataIndex: "AllocatedQty",
          key: "AllocatedQty",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "分配精华液数量",
          dataIndex: "SmgrQty",
          key: "SmgrQty",
          ellipsis: true,
          align: "center",
          width: 120,
        },
        {
          title: "创建人",
          dataIndex: "CreateUserName",
          key: "CreateUserName",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "创建时间",
          dataIndex: "CreateDtName",
          key: "CreateDtName",
          ellipsis: true,
          align: "center",
          width: 200,
        },
        {
          title: "修改人",
          dataIndex: "ModifyUserName",
          key: "ModifyUserName",
          ellipsis: true,
          align: "center",
          width: 100,
        },
        {
          title: "修改时间",
          dataIndex: "ModifyDtName",
          key: "ModifyDtName",
          ellipsis: true,
          align: "center",
          width: 200,
        },
        {
          title: "操作",
          fixed: "right",
          dataIndex: "operate",
          width: 200,
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ], //明细表头
      semiMGoodsDistributePlanPage: {
        data: [],
        PageIndex: 1,
        PageSize: 100,
        TotalNumber: 0,
        TotalPage: 0,
        isEdit: false, //是否修改明细
        isShow: false,
        rowKey: [],
        rowItemList: [],
        item: {}, //添加的明细对象
      }, //当前明细
      currentPlanPage: {}, //当前明细
      assignedPlanPage: {
        isShow: false,
      }, //已分配
      isPlanEditShow: false,
      isPlanShow: false,
      pageSizeOptions: ["30", "50", "100"],
      WSTypeList: [],
      QSegmentList: [],
      DicStatus: [
        {
          type: 0,
          name: "ERP下达",
        },
        {
          type: 1,
          name: "待审核",
        },
        {
          type: 2,
          name: "已下发",
        },
        {
          type: 3,
          name: "生产中",
        },
        {
          type: 6,
          name: "结束生产",
        },
      ], //订单状态
      DicIsDistribute: [
        {
          type: 0,
          name: "否",
        },
        {
          type: 1,
          name: "是",
        },
      ], //是否已分配
      leftWidth: 800, // 左侧表格宽度
      rightWidth: 800, // 右侧表格宽度
      isResizing: false, // 是否正在调整大小
      startX: 0, // 开始调整时的X坐标
      startLeftWidth: 0, // 开始调整时的左侧宽度
      startRightWidth: 0, // 开始调整时的右侧宽度
      globalLoading: false, // 新增全局loading状态
    };
  },
  created() {
    let that = this;
    that.searchItem.createStartDt = that.dateExt.getDay(-30);
    that.defaulttimeList[0] = that.searchItem.createStartDt;
    that.searchItem.createEndDt = that.dateExt.getDay(30);
    that.defaulttimeList[1] = that.searchItem.createEndDt;

    that.GetWorkShopTypesAllFun();
    that.getData();
  },
  mounted() {
    //this.getData();
  },

  methods: {
    //获取厂区列表
    async GetWorkShopTypesAllFun() {
      let that = this;
      let res = await GetWorkShopTypesAll(10);
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.WSType, name: item.WSName });
        });
        that.WSTypeList = wtList;
      } else {
        that.$message.error(res.Message);
      }
    },
    //选中厂区
    handleChange(value) {
      let that = this;
      if (value) {
        that.GetSegmentsAllFun(that.searchItem.WSType, true);
      }
    },
    //获取车间列表
    GetSegmentsAllFun: debounce(async function (WSType, ispplist = false) {
      let that = this;
      let SegSegmentID = ["5D494A1E-5F24-4036-9350-2E442A19FE87"];

      let res = await GetSegments({
        SegSegmentID: SegSegmentID,
        WSTypeList: WSType,
      });
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.SegmentID, name: item.SegmentName });
        });
        if (ispplist) {
          that.QSegmentList = wtList;
        } else {
          that.PPQSegmentList = wtList;
        }
      } else {
        that.$message.error(res.Message);
      }
    }),
    /** 点击查询明细 */
    customRow(record, index) {
      let that = this;
      return {
        style: {
          "background-color":
            record.PackingPlanID === that.currentRow?.PackingPlanID
              ? "#E6F7FF"
              : "",
        },
        on: {
          // 鼠标单击行
          click: (event) => {
            // 记录当前点击的行标识
            that.currentRow = record;
            that.getDetailDataFun();
            that.getPlanDataFun();
          },
        },
      };
    },

    /** 查询精华液预分配表格 */
    async getData() {
      this.globalLoading = true;
      // 记录当前选中行的 PackingPlanID
      const selectedPackingPlanID = this.currentRow?.PackingPlanID;

      // 取消所有勾选状态
      this.topRowKey = [];
      this.topRow = [];
      this.semiMGoodsDistributeDetailPage.rowKey = [];
      this.semiMGoodsDistributeDetailPage.rowItemList = [];
      this.semiMGoodsDistributePlanPage.rowKey = [];
      this.semiMGoodsDistributePlanPage.rowItemList = [];

      try {
        let { Data } = await getSemiMGoodsDistributeList(this.searchItem);
        let { pageIndex, pageSize } = this.searchItem.pageRequestModel;
        Data.Data.map((item, index) => {
          item.num = (pageIndex - 1) * pageSize + index + 1;
          item.ModifyDtName = item.ModifyDt
            ? moment(item.ModifyDt).format("YYYY-MM-DD HH:mm:ss")
            : "";
          item.CreateDtName = item.CreateDt
            ? moment(item.CreateDt).format("YYYY-MM-DD HH:mm:ss")
            : "";
        });
        this.dataPage = Data;
        this.semiMGoodsDistributeDetailPage.data = [];

        let newSelectedRow;
        if (selectedPackingPlanID) {
          // 若之前有选中行，尝试在新数据中找到该行
          newSelectedRow = Data.Data.find(
            (item) => item.PackingPlanID === selectedPackingPlanID
          );
        }
        if (!newSelectedRow && Data.Data.length > 0) {
          // 若之前未选中行或在新数据中未找到之前选中的行，选择第一行
          newSelectedRow = Data.Data[0];
        }

        if (newSelectedRow) {
          this.currentRow = newSelectedRow;
          this.getDetailDataFun();
          this.getPlanDataFun();
        } else {
          this.currentRow = {};
        }
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.globalLoading = false;
      }
      this.topAddShow = false;
      this.topEditShow = false;
    },

    /** 批量删除精华液预分配 */
    async delDatas() {
      let that = this;
      this.$confirm({
        title: "提示",
        content: `是否确认删除选中${that.topRow.length}项`,
        async onOk() {
          try {
            let res = await delSemiMGoodsDistributeList(that.topRow);
            if (res.Status == 10000) {
              that.$message.success("删除成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },

    /** 时间选择器的样式填充 */
    getcurrentStyle(current, today) {
      const style = {};
      if (current.date() === 1) {
        style.border = "1px solid #1890ff";
        style.borderRadius = "50%";
      }
      return style;
    },
    /** 精华液选中项 */
    topTableChangeFun(selectedRowKeys, selectedRows) {
      this.topRow = selectedRows; //选中项信息
      this.topRowKey = selectedRowKeys; //选中项ID
    },

    /** 添加预分配精华液 */
    addFun(item) {
      if (
        item &&
        item.SemiMGoodsDistributeID != "00000000-0000-0000-0000-000000000000"
      ) {
        this.$message.warning("当前计划单已新增预分配单");
        return;
      }
      item.SemiMGoodsDistributeID = "00000000-0000-0000-0000-000000000000"; // 重置ID
      item.AllocationRatio = 5;
      this.essenceItems = [];
      this.essenceItems.push(item);

      this.topAddShow = true;
      this.dataPage.isEdit = false;
    },

    /** 添加预分配精华液 */
    addMultipleFun() {
      if (this.topRow.length === 0) {
        this.$message.warning("请至少选择一项计划单");
        return;
      }

      // 检查是否所有选中项都未创建预分配单
      const hasCreatedItems = this.topRow.some(
        (item) =>
          !item.SemiMGoodsDistributeID ||
          item.SemiMGoodsDistributeID !== "00000000-0000-0000-0000-000000000000"
      );

      if (hasCreatedItems) {
        this.$message.warning("选中的计划单中已有预分配单，请重新选择");
        return;
      }
      if (this.topRow.length > 1) {
        // 检查销售单号是否一致
        const firstSellOrderNo = this.topRow[0].SellOrderNo;
        const hasDifferentSellOrderNo = this.topRow.some(
          (item) => item.SellOrderNo !== firstSellOrderNo
        );

        if (hasDifferentSellOrderNo) {
          this.$message.warning("选中的计划单销售单号不一致，请重新选择");
          return;
        }
        // let mflat = 0;
        // // 检查需求/分配数是否只有一项
        // this.topRow.forEach((item) => {
        //   if (
        //     item.SemiMGoodsDistributeDetailDtos &&
        //     item.SemiMGoodsDistributeDetailDtos.length > 1
        //   ) {
        //     mflat = 1;
        //     return;
        //   }
        // });
        // if (mflat == 1) {
        //   this.$message.warning(
        //     "选中的计划单存在多个精华液，不允许多个一起分配，请重新选择"
        //   );
        //   return;
        // }
      }
      this.essenceItems = this.topRow;

      this.essenceItems.forEach((item) => {
        item.SemiMGoodsDistributeID = "00000000-0000-0000-0000-000000000000"; // 重置ID
        item.AllocationRatio = 5;
      });

      this.topAddShow = true;
      this.dataPage.isEdit = false;
    },
    /** 修改预分配精华液 */
    editFun(item) {
      this.essenceItem = JSON.parse(JSON.stringify(item));
      this.topEditShow = true;
      this.dataPage.isEdit = true;
    },
    /** 删除预分配精华液 */
    async delFun(item) {
      let that = this;
      this.$confirm({
        title: "提示",
        content: `是否删除【${item.OrderCode}】项`,
        async onOk() {
          try {
            let res = await delSemiMGoodsDistribute(item);
            if (res.Status == 10000) {
              that.$message.success("删除成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },
    /** 删除预分配精华液 */
    async delFun(item) {
      let that = this;
      this.$confirm({
        title: "提示",
        content: `是否删除【${item.OrderCode}】项`,
        async onOk() {
          try {
            let res = await delSemiMGoodsDistribute(item);
            if (res.Status == 10000) {
              that.$message.success("删除成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },
    /** 下发预分配精华液 */
    async issueFun(item) {
      let that = this;
      let content = "是否下发【" + item.OrderCode + "】项";
      if (item.DistributeState == 2) {
        content = "是否反下发【" + item.OrderCode + "】项";
      }

      this.$confirm({
        title: "提示",
        content: content,
        async onOk() {
          try {
            let res = await issueSemiMGoodsDistribute(item);
            if (res.Status == 10000) {
              that.$message.success("操作成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },
    //批量下发
    async issueMultipleFun() {
      let that = this;
      if (that.topRow.length === 0) {
        that.$message.warning("请至少选择一项分配单");
        return;
      }
      // 检查是否所有选中项都未创建预分配单
      const hasCreatedItems = that.topRow.some(
        (item) =>
          !item.SemiMGoodsDistributeID ||
          item.SemiMGoodsDistributeID === "00000000-0000-0000-0000-000000000000"
      );

      if (hasCreatedItems) {
        that.$message.warning("选中的计划单中有没创建分配单，请重新选择");
        return;
      }

      // 检查是否所有选中项都未下发
      const hasStateItems = that.topRow.some(
        (item) => item.DistributeState === 2
      );

      if (hasStateItems) {
        that.$message.warning("选中的计划单中有下发的分配单，请重新选择");
        return;
      }

      let sflat = 0;
      let fflat = 0;

      // 使用 await 等待确认框返回
      const confirmResult = await new Promise((resolve) => {
        that.$confirm({
          title: "提示",
          content: "是否下发【" + that.topRow.length + "】项",
          async onOk() {
            // 使用 Promise.all 等待所有异步操作完成
            await Promise.all(
              that.topRow.map(async (item) => {
                try {
                  let res = await issueSemiMGoodsDistribute(item);
                  if (res.Status == 10000) {
                    sflat++;
                  } else {
                    fflat++;
                  }
                } catch (e) {
                  that.$message.error(e);
                  fflat++;
                }
              })
            );
            resolve(true); // 用户点击确定
          },
          onCancel() {
            resolve(false); // 用户点击取消
          },
        });
      });

      // 只有当用户点击确定时才执行后续操作
      if (confirmResult) {
        if (sflat > 0) {
          that.getData();
          that.$message.success(
            "操作成功[" + sflat + "个],失败[" + fflat + "个]"
          );
        } else {
          that.$message.error("全部操作失败");
        }
      }
    },
    /** 查询预分配明细 */
    async getDetailDataFun() {
      this.globalLoading = true;
      this.semiMGoodsDistributeDetailSearch.PackingPlanID =
        this.currentRow.PackingPlanID;
      try {
        let { Data } = await getDetailData(
          this.semiMGoodsDistributeDetailSearch
        );
        let { pageIndex, pageSize } =
          this.semiMGoodsDistributeDetailSearch.pageRequestModel;
        Data.Data.map((item, index) => {
          item.num = (pageIndex - 1) * pageSize + index + 1;
          item.ModifyDtName = item.ModifyDt
            ? moment(item.ModifyDt).format("YYYY-MM-DD HH:mm:ss")
            : "";
          item.CreateDtName = item.CreateDt
            ? moment(item.CreateDt).format("YYYY-MM-DD HH:mm:ss")
            : "";
        });
        this.semiMGoodsDistributeDetailPage.data = Data.Data;
        this.isDetailShow = false;
        this.isDetailEditShow = false;
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.globalLoading = false;
      }
    },
    /** 查询投料预分配明细 */
    async getPlanDataFun() {
      this.globalLoading = true;
      this.semiMGoodsDistributePlanSearch.PackingPlanID =
        this.currentRow.PackingPlanID;
      try {
        let { Data } = await getSemiMGoodsDistributePlanList(
          this.semiMGoodsDistributePlanSearch
        );
        let { pageIndex, pageSize } =
          this.semiMGoodsDistributePlanSearch.pageRequestModel;
        Data.Data.map((item, index) => {
          item.num = (pageIndex - 1) * pageSize + index + 1;
          item.ModifyDtName = item.ModifyDt
            ? moment(item.ModifyDt).format("YYYY-MM-DD HH:mm:ss")
            : "";
          item.CreateDtName = item.CreateDt
            ? moment(item.CreateDt).format("YYYY-MM-DD HH:mm:ss")
            : "";
        });
        this.semiMGoodsDistributePlanPage.data = Data.Data;
        this.isPlanShow = false;
        this.isPlanEditShow = false;
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.globalLoading = false;
      }
    },
    /** 新增预分配明细 */
    addDetailsFun() {
      if (
        this.currentRow?.SemiMGoodsDistributeID == null ||
        this.currentRow?.SemiMGoodsDistributeID == undefined ||
        this.currentRow?.SemiMGoodsDistributeID ==
          "00000000-0000-0000-0000-000000000000"
      ) {
        return this.$message.warning("请先添加预分配单");
      }
      this.isDetailShow = true;
      this.semiMGoodsDistributePlanSearch.PackingPlanID =
        this.currentRow.PackingPlanID;
      this.semiMGoodsDistributeDetailPage.item = {};
      this.semiMGoodsDistributeDetailPage.isEdit = false;
    },
    //添加投料单
    addPlansFun() {
      this.isPlanShow = true;
      this.semiMGoodsDistributePlanPage.item = {};
      this.semiMGoodsDistributePlanPage.isEdit = false;
    },
    /** 修改预分配明细 */
    editDetailsFun(item) {
      this.isDetailEditShow = true;
      this.semiMGoodsDistributeDetailPage.item = JSON.parse(
        JSON.stringify(item)
      );
      this.semiMGoodsDistributeDetailPage.isEdit = true;
    },
    /** 修改预分配投料单明细 */
    editPlansFun(item) {
      this.isPlanEditShow = true;
      this.semiMGoodsDistributePlanPage.item = JSON.parse(JSON.stringify(item));
      this.semiMGoodsDistributePlanPage.isEdit = true;
    },
    /**  选中预分配明细项 */
    bottomTableChangeFun(selectedRowKeys, selectedRows) {
      this.semiMGoodsDistributeDetailPage.rowItemList = selectedRows; //选中项信息
      this.semiMGoodsDistributeDetailPage.rowKey = selectedRowKeys; //选中项ID
    },
    /**  选中预分配明细项 */
    bottomPlanTableChangeFun(selectedRowKeys, selectedRows) {
      this.semiMGoodsDistributePlanPage.rowItemList = selectedRows; //选中项信息
      this.semiMGoodsDistributePlanPage.rowKey = selectedRowKeys; //选中项ID
    },
    //关闭弹窗
    closeDetailForm() {
      this.isDetailShow = false;
      this.isDetailEditShow = false;
    },
    //关闭弹窗
    closePlanForm() {
      this.isPlanShow = false;
      this.isPlanEditShow = false;
    },
    /** 删除预分配明细 */
    delDetailsFun(item) {
      let that = this;
      this.$confirm({
        title: "提示",
        content: `是否删除【${item.MaterialName}(${item.MaterialCode})】项`,
        async onOk() {
          try {
            let res = await delSemiMGoodsDistributeDetail(item);
            if (res.Status == 10000) {
              that.$message.success("删除成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },
    /** 删除预分配投料单明细 */
    delPlansFun(item) {
      let that = this;
      this.$confirm({
        title: "提示",
        content: `是否删除【${item.PlanNo}】项`,
        async onOk() {
          try {
            let res = await delSemiMGoodsPlanRelationList([item]);
            if (res.Status == 10000) {
              that.$message.success("删除成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },
    /** 批量删除预分配明细 */
    allDelDetailsFun() {
      let that = this;
      this.$confirm({
        title: "提示",
        content: `是否确认删除选中${that.semiMGoodsDistributeDetailPage.rowItemList.length}项`,
        async onOk() {
          try {
            let res = await delSemiMGoodsDistributeDetailList(
              that.semiMGoodsDistributeDetailPage.rowItemList
            );
            if (res.Status == 10000) {
              that.$message.success("删除成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },
    /** 批量删除预分配明细 */
    allDelPlansFun() {
      let that = this;
      this.$confirm({
        title: "提示",
        content: `是否确认删除选中${that.semiMGoodsDistributePlanPage.rowItemList.length}项`,
        async onOk() {
          try {
            let res = await delSemiMGoodsPlanRelationList(
              that.semiMGoodsDistributePlanPage.rowItemList
            );
            if (res.Status == 10000) {
              that.$message.success("删除成功");
              that.getData();
            }
          } catch (e) {
            that.$message.error(e);
          }
        },
        onCancel() {},
      });
    },

    /** 查看预分配单已领料 */
    assignedShow(item) {
      this.essenceItem = item;
      this.assignedPage.isShow = true;
    },

    /** 查看已分配表单 */
    assignedPlanShow(item) {
      this.essencePlanItem = item;
      this.assignedPlanPage.isShow = true;
    },
    /** 筛选选择时间 */
    onTime(e, e1) {
      let that = this;
      that.searchItem.createStartDt = that.dateExt.showDateTime(e[0]);
      that.searchItem.createEndDt = that.dateExt.showDateTime(e[1]);
    },

    /** 分页选择 */
    onChange(page, pageSize) {
      this.searchItem.pageRequestModel.pageIndex = page;
      this.searchItem.pageRequestModel.pageSize = pageSize;
      this.getData();
    },

    /** 条数选择 */
    onShowsizeChange(current, size) {
      this.searchItem.pageRequestModel.pageIndex = current;
      this.searchItem.pageRequestModel.pageSize = size;
      this.getData();
    },

    // 列宽拖拽相关方法
    handleResizeStart(e, index) {
      const { colResize } = this.searchItem;
      colResize.isDragging = true;
      colResize.startX = e.clientX;

      // 根据索引获取对应表格的列宽
      if (index >= 20 && index < 40) {
        // 精华液信息表格
        colResize.startWidth = this.detailColumns[index - 19].width;
      } else if (index >= 40) {
        // 投料单信息表格
        colResize.startWidth = this.detailPlanColumns[index - 39].width;
      } else {
        // 主表格
        colResize.startWidth = this.topColumns[index].width;
      }

      colResize.currentColIndex = index;
      document.addEventListener("mousemove", this.handleResizing);
      document.addEventListener("mouseup", this.handleResizeEnd);
    },

    handleResizing(e) {
      const { colResize } = this.searchItem;
      if (!colResize.isDragging) return;
      const delta = e.clientX - colResize.startX;
      const newWidth = Math.max(50, colResize.startWidth + delta);

      // 根据当前拖拽的列索引更新对应表格的列宽
      if (colResize.currentColIndex >= 20 && colResize.currentColIndex < 40) {
        // 精华液信息表格
        this.detailColumns[colResize.currentColIndex - 19].width = newWidth;
      } else if (colResize.currentColIndex >= 40) {
        // 投料单信息表格
        this.detailPlanColumns[colResize.currentColIndex - 39].width = newWidth;
      } else {
        // 主表格
        this.topColumns[colResize.currentColIndex].width = newWidth;
      }
    },

    handleResizeEnd() {
      const { colResize } = this.searchItem;
      colResize.isDragging = false;
      colResize.currentColIndex = -1;
      document.removeEventListener("mousemove", this.handleResizing);
      document.removeEventListener("mouseup", this.handleResizeEnd);
    },

    /** 精华液信息表格行点击 */
    customDetailRow(record, index) {
      let that = this;
      return {
        on: {
          click: (event) => {
            // 更新选中状态
            const selectedRowKeys = that.semiMGoodsDistributeDetailPage.rowKey;
            const selectedRows =
              that.semiMGoodsDistributeDetailPage.rowItemList;
            const key = record.SemiMGoodsDistributeDetailID;
            const index = selectedRowKeys.indexOf(key);

            if (index >= 0) {
              // 如果已经选中，则取消选中
              selectedRowKeys.splice(index, 1);
              selectedRows.splice(index, 1);
            } else {
              // 如果未选中，则添加选中
              selectedRowKeys.push(key);
              selectedRows.push(record);
            }

            // 更新选中状态
            that.semiMGoodsDistributeDetailPage.rowKey = selectedRowKeys;
            that.semiMGoodsDistributeDetailPage.rowItemList = selectedRows;
          },
        },
      };
    },

    /** 投料单信息表格行点击 */
    customPlanRow(record, index) {
      let that = this;
      return {
        on: {
          click: (event) => {
            // 更新选中状态
            const selectedRowKeys = that.semiMGoodsDistributePlanPage.rowKey;
            const selectedRows = that.semiMGoodsDistributePlanPage.rowItemList;
            const key = record.SemiMGoodsPlanRelationID;
            const index = selectedRowKeys.indexOf(key);

            if (index >= 0) {
              // 如果已经选中，则取消选中
              selectedRowKeys.splice(index, 1);
              selectedRows.splice(index, 1);
            } else {
              // 如果未选中，则添加选中
              selectedRowKeys.push(key);
              selectedRows.push(record);
            }

            // 更新选中状态
            that.semiMGoodsDistributePlanPage.rowKey = selectedRowKeys;
            that.semiMGoodsDistributePlanPage.rowItemList = selectedRows;
          },
        },
      };
    },
  },
  updated() {
    this.$nextTick(() => {});
  },
  watch: {
    defaulttimeList: {
      handler(newV, oldV) {
        if (newV) {
          if (newV.length == 0) {
            this.searchItem.createStartDt = null;
            this.searchItem.createEndDt = null;
          }
        }
      },
      immediate: true, // 重点
      deep: true, // 重点
    },
  },
};
</script>
<style lang="less" scoped>
.operation {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  overflow: hidden;
  height: 100%;
  position: relative;
  .top {
    flex: 1;
    margin: 0.625rem;
    header {
      margin-bottom: 0.625rem;
    }
    h3 {
      display: flex;
      align-items: center;
      .tip {
        height: 5px;
        width: 5px;
        background-color: #009999;
        display: inline-block;
        margin-right: 10px;
      }
    }
    .table-paging {
      margin: 1rem 0;
      text-align: right;
    }
  }
  .bottom {
    flex: 1;
    section {
      display: flex;
      flex-direction: column;
    }
  }
  .operation-search {
    display: flex;
    justify-content: flex-end;
    flex-direction: column;
    border-bottom: 2px solid #f0f2f5;
    .selectwidth {
      width: 15rem;
    }
    .selectrightwidth {
      width: 7rem;
    }
    .btn-ant-form {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      color: rgba(0, 0, 0, 0.65);
      font-size: 14px;
      font-variant: tabular-nums;
      line-height: 1.5;
      list-style: none;
      font-feature-settings: "tnum";
      display: flex;
      justify-content: flex-end;
    }
  }
  .total-info {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 16px;
    .info-item {
      display: flex;
      align-items: center;
      margin-right: 32px;
      &:last-child {
        margin-right: 0;
      }
      .label {
        color: rgba(0, 0, 0, 0.65);
        margin-right: 8px;
        font-size: 14px;
      }
      .value {
        color: #1890ff;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
}
// 添加样式
::v-deep .ant-table-thead > tr > th {
  position: relative;
  user-select: none;

  &::after {
    content: "";
    position: absolute;
    right: -3px !important; // 扩大可拖拽区域
    top: 0;
    z-index: 1;
    width: 5px;
    height: 100%;
    cursor: col-resize;
    background-color: transparent;
    transition: background-color 0.3s;
  }

  &:hover::after {
    background-color: #1890ff;
  }
}

.ant-table-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table-container {
  display: flex;
  align-items: flex-start;
  margin-top: 16px;
  position: relative;
  height: calc(100vh - 200px);
}

.table-wrapper {
  flex-shrink: 0;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-title {
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.resize-handle {
  width: 8px;
  background: #f0f0f0;
  cursor: col-resize;
  transition: background-color 0.3s;

  &:hover {
    background: #1890ff;
  }

  &::after {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    background: #e8e8e8;
  }
}
.small-button {
  // 调整按钮的内边距和高度，使其接近 a-tag 的大小
  padding: 0 8px;
  height: 22px;
  line-height: 22px;
  font-size: 12px;
  display: inline-block;
  border-radius: 2px;
  margin-right: 8px;
  text-align: center;
  cursor: pointer;
  // 可以根据需要调整其他样式属性
}
.action-tag {
  margin-right: 8px;

  &:last-child {
    margin-right: 0;
  }
}
.red-button {
  background-color: #e04949;
  color: #ffffff;

  &[disabled] {
    background-color: #f5f5f5;
    color: rgba(0, 0, 0, 0.25);
    border-color: #d9d9d9;
    text-shadow: none;
    box-shadow: none;
  }
}
/* 添加单元格换行样式 */
/deep/ .ant-table td {
  white-space: pre-line;
}
.button {
  margin: 10px;
}
</style>
